package com.zidongxiangxi.clock.server.message.handler;

import com.alibaba.fastjson.JSON;
import com.zidongxiangxi.clock.http.enums.ClockInputEventEnum;
import com.zidongxiangxi.clock.http.message.ClockMessage;
import com.zidongxiangxi.clock.http.message.CreateClockMessageBody;
import com.zidongxiangxi.clock.server.business.ClockBusiness;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 创建闹钟mq处理类
 *
 * @author chenxudong
 * @date 2021/02/01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CreateClocMessageHandler extends AbstractClockMessageHandler {
    private final ClockBusiness clockBusiness;

    @Override
    public boolean canHandle(ClockMessage<String> clockMqMessage) {
        return Objects.nonNull(clockMqMessage) && Objects
            .equals(clockMqMessage.getEventType(), ClockInputEventEnum.CREATE_CLOCK.getCode());
    }

    @Override
    public void handle(ClockMessage<String> clockMessage) {
        String msgBody = clockMessage.getMsgBody();
        CreateClockMessageBody message = JSON.parseObject(msgBody, CreateClockMessageBody.class);
        if (Objects.isNull(message)) {
            return;
        }
        try {
            clockBusiness.createClock(message.getApplication(), message.getBusinessId(), message.getPayload(),
                message.getTargetRingAt(), message.getLatestRingAt());
        } catch (Exception e) {
            log.error("fail to create clock, message: " + JSON.toJSONString(clockMessage), e);
        }
    }
}
